#include "stdafx.h"
#include "..\headers\StateManager.h"
#include "..\headers\State.h"

namespace ne{

StateManager::StateManager(void) : m_currentState(nullptr), m_nextState(nullptr){}
StateManager::~StateManager(void){}

void StateManager::Init(){
}

bool StateManager::Update(GameTime* gameTime){
	if (m_nextState != nullptr){
		if (m_currentState != nullptr){
			m_currentState->Exit();
		}
		m_currentState = m_nextState;
		m_currentState->Enter();
		m_nextState = nullptr;
	}
	if (m_currentState != nullptr){
		return m_currentState->Update(gameTime);
	}
	return false;
}

State* StateManager::FindByName(const Ogre::String& name){
	if (!m_states.empty()){
		for (unsigned int i = 0; i < m_states.size(); i++){
			if (m_states[i]->GetName() == name){
				return m_states[i];
			}
		}
	}
	return nullptr;
}

void StateManager::ChangeState(State* state){
	m_nextState = state;
}

void StateManager::AddState(State* state){
	if (FindByName(state->GetName()) == nullptr){
		m_states.push_back(state);
	}
	else {
		System::Log("Warning: state" + state->GetName() + " already exists. This state was not added.");
	}
}

void StateManager::Shut(){
	if (m_currentState != nullptr){
		m_currentState->Exit();
	}
	if (!m_states.empty()){
		for (unsigned int i = 0; i < m_states.size(); i++){
			delete m_states[i];
			m_states[i] = nullptr;
		}
		m_states.clear();
	}
}

}